<template>
	<view class="container">
		<u-form :model="form" ref="uForm" label-position="top" :error-type="['toast']">
			<u-form-item label="宝宝">
				<view class="children-view">
					<children-list-view :addShow="addShow1()" @showClasses="showClasses" :childrenList="childrenList"
						@itemClick="childrenItemClick"></children-list-view>
				</view>
			</u-form-item>
			<u-form-item label="选择日期" prop="eventTime">
				<u-input v-model="form.eventTimeStr" type="select" placeholder="请选择时间" @click="timeShow = true" />
			</u-form-item>
			<u-form-item label="症状">
				<u-checkbox-group width="25%" >
					<u-checkbox v-model="item.check" v-for="(item, index) in radioList" :key="index" :name="item.name"
						:disabled="item.disabled" shape="circle">
						{{ item.name }}
					</u-checkbox>
				</u-checkbox-group>
			</u-form-item>
			<u-form-item label="症状(其他)" prop="symptom">
				<u-input v-model="form.symptom" />
			</u-form-item>
			<u-form-item label="托药列表" prop="medicines">
				<view class="time-view">
					<view v-for="(item, index) in form.medicines" @click="medicinesClick(item)">
						<text>{{item.name}}</text>
						<u-icon name="trash" class="del" @click="timeDelClick(index)"></u-icon>
					</view>
				</view>
				<u-icon slot="right" name="plus-circle" @click="addClick" size="48"></u-icon>
			</u-form-item>
			<u-form-item label="医嘱照片">
				<u-upload ref="uUploadAdvice" width="140" height="140"
					:file-list="adviceList"
					:action="action" :form-data="formData" :header="header"
					:auto-upload="true">
				</u-upload>
			</u-form-item>
			<u-form-item label="委托函照片">
				<u-upload ref="uUploadAttorney" width="140" height="140"
					:file-list="attorneyList"
					:action="action" :form-data="formData" :header="header"
					:auto-upload="true">
				</u-upload>
			</u-form-item>
			<u-form-item label="委托签名">
				<view style="padding: 10rpx;">
					<u-image width="140" height="140" :src="assignImgSVG" @click="startSign">
						<view slot="error" style="font-size: 24rpx;" @click="startSign">签名</view>
					</u-image>
				</view>
			</u-form-item>
		</u-form>
		<u-button class="action-view" @click="saveClick">保存</u-button>
		<u-picker v-model="timeShow" mode="time" :params="params" @confirm="confirmTime"></u-picker>
		<children-select-view ref="popupConpare" @confirm="confirm" :single="true"></children-select-view>
		<Signature ref="sig" v-model="assignImgSVG" v-show="signatureShow"></Signature>
	</view>
</template>

<script>
	import {
		addRecordHandover,
		getRecordHandover,
		uploadRecordImg,
		uploadRecordImgByPath,
		addRecordHandoverByParent,
		uploadRecordSvgByPath
	} from '@/api/record.js'
	import ChildrenListView from '@/components/children-list-view.vue'
	import ChildrenSelectView from '@/components/children-select-view.vue'
	import Signature from './components/sin-signature/sin-signature.vue'
	import {
		formatDateByTimestamp
	} from '@/utils/utils.js'
	import { http } from '@/api/service.js'
	import recordMixin from './mixins/index.js'
	export default {
		mixins: [recordMixin],
		components: {
			ChildrenListView,
			ChildrenSelectView,
			Signature
		},
		data() {
			return {
				action: '',
				formData: {
					'recordType': 'handover'
				},
				header: {
					ticket: '',
				},

				form: {
					eventTime: '',
					eventTimeStr: '',
					situation: '',
					symptom: '',
					
					medicines: [],
					adviceImg: '',
					attorneyImg: '',
					assignImg: ''
					// guardian: 'guardian',
					// guardianPhoto: 'guardianPhoto'
				},
				adviceList: [],
				attorneyList: [],
				assignImgSVG: '',
				
				rules: {
					eventTime: [{
						required: true,
						message: '请选择喂食时间',
					}, ],
					situation: [{
						required: true,
						message: '请填写症状',
					}, ],
					medicines: [
						{
							validator: (rule, value, callback) => {
								console.log(value.length > 0);
								return value.length > 0;
							},
							message: '请先添加交接的药品',
						}
					]
				},

				radioList: [{
						name: '咳嗽',
						check: false
					},
					{
						name: '发烧',
						check: false
					},
					{
						name: '流鼻涕',
						check: false
					},
					{
						name: '红斑',
						check: false
					},
					{
						name: '腹泻',
						check: false
					},
					{
						name: '便秘',
						check: false
					},
					{
						name: '呕吐',
						check: false
					},
					{
						name: '结膜炎',
						check: false
					},
				],

				timeShow: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false,
					timestamp: true,
				},

				signatureShow: false,
			};
		},
		onLoad(options) {
			if (this.appType === 'app-p' || this.appType === 'mp-p') {
				this.action = `${http.config.baseURL}wx/api/upload/file`;
			} else {
				// this.action = `${http.config.baseURL}pad/upload/record_img`;
					this.action = `${http.config.baseURL}wx/api/upload/file`;
			}
			this.header.ticket = uni.getStorageSync('ticket');
		},
		methods: {
			async startSign() {
				this.signatureShow = true;
				let s = await this.$refs.sig.getSyncSignature();
				this.form.assignImg = s;
				this.signatureShow = false;
			},

			async addRecord() {
				uni.showLoading({})
				//选中的学生
				let childIds = '';
				for (let index in this.childrenList) {
					let item = this.childrenList[index];
					childIds += `,${item.id}`;
				}
				if (childIds.length > 0) {
					childIds = childIds.substring(1);
				}
				this.form.childId = childIds
				
				let situation = '';
				for (let index in this.radioList) {
					let item = this.radioList[index];
					if (item.check) {
						situation += `|${item.name}`;
					}
				}
				if (situation.length > 0) {
					situation = situation.substring(1);
				}
				if (this.$u.test.isEmpty(this.form.symptom)) {
					this.form.situation = situation;
				} else {
					this.form.situation = `${this.form.symptom};${situation}`
				}
				
				let files = this.$refs.uUploadAdvice.lists;
				console.log(files);
				let adviceImg = '';
				for (let index in files) {
					let item = files[index];
					if (this.$u.test.isEmpty(item.response)) {
						adviceImg += `|${item.url}`
					} else {
						adviceImg += `|${item.response.data}`
					}
				}
				if (adviceImg.length > 0) {
					adviceImg = adviceImg.substring(1);
				}
				this.form.adviceImg = adviceImg;
				
				files = this.$refs.uUploadAttorney.lists;
				let attorneyImg = '';
				for (let index in files) {
					let item = files[index];
					if (this.$u.test.isEmpty(item.response)) {
						attorneyImg += `|${item.url}`
					} else {
						attorneyImg += `|${item.response.data}`
					}
				}
				if (attorneyImg.length > 0) {
					attorneyImg = attorneyImg.substring(1);
				}
				this.form.attorneyImg = attorneyImg;
				
				if (!this.$u.test.isEmpty(this.form.assignImg)){
				let data = await uploadRecordSvgByPath(this.form.assignImg)
					// let data = await uploadRecordImgByPath(this.form.assignImg);
					this.form.assignImg = data.data;
				} else {
					this.form.assignImg = this.assignImgSVG;
				}
				if (!this.$u.test.isEmpty(this.recordId)) {
					this.form.id = this.recordId
				}
				
				let param = JSON.stringify(this.form);
				console.log(param);
				if (this.appType === 'app-p' || this.appType === 'mp-p') {
					addRecordHandoverByParent(param).then(res => {
						console.log(res);
						uni.hideLoading();
						uni.navigateBack({});
					}).catch(err => {
						uni.hideLoading();
					})
				} else {
					addRecordHandover(param).then(res => {
						console.log(res);
						uni.hideLoading();
						uni.navigateBack({});
					}).catch(err => {
						uni.hideLoading();
					})
				}
			},

			confirmTime(res) {
				console.log(res);
				this.form.eventTime = res.timestamp;
				this.form.eventTimeStr = formatDateByTimestamp(res.timestamp, 'yyyy/mm/dd')
			},
			
			addClick() {
				let that = this;
				uni.navigateTo({
					url: '/pages_sub/record/handover-medicines-page',
					events: {
						addSuccessEvent: function(data) {
							console.log(data);
							that.form.medicines.push(data);
						},
					}
				})
			},
			
			medicinesClick(item) {
				console.log(item)
			},
			
			timeDelClick(index) {
				this.form.medicines.splice(index, 1);
			},
			
			getRecord() {
				console.log(this.recordId)
				if (this.$u.test.isEmpty(this.recordId)) {
					return;
				}
				uni.showLoading({})
				const params = {
					id: this.recordId,
					childId: this.defaultChildren.id
				}
				getRecordHandover(params).then(res => {
					console.log(res)
					uni.hideLoading()
					this.init(res.data)
				})
			},
			
			init(data) {
				let symptom = ''
				const { situation, adviceImg, attorneyImg, assignImg, medicines, eventTime } = data;
				const situationList = situation.split(';');
				if (situationList.length > 1) {
					symptom = situationList[0]
				}
				const radioList = this.radioList.map(x => {
					return {
						name: x.name,
						check: situation.indexOf(x.name) !== -1
					}
				})
				this.radioList = radioList
				
				let adviceList = [];
				if (!this.$u.test.isEmpty(adviceImg)) {
					adviceList = adviceImg.split('|').map(x => {
						return {
							url: x
						}
					})
				}

				let attorneyList = [];
				if (!this.$u.test.isEmpty(attorneyImg)) {
					attorneyList = attorneyImg.split('|').map(x => {
						return {
							url: x
						}
					})
				}
							
				const eventTimeStr = formatDateByTimestamp(parseFloat(eventTime), 'yyyy/mm/dd')
				const form = {
					eventTime,
					eventTimeStr,
					situation,
					symptom,

					medicines
				};
				this.form = form;
				this.assignImgSVG = assignImg;
				this.adviceList = adviceList;
				this.attorneyList = attorneyList;
			},
			
			addShow1() {
				if (this.appType === 'app-p' || this.appType === 'mp-p') {
					return false;
				}
				return this.$u.test.isEmpty(this.recordId)
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: $app-page-bg-color;
	}
</style>
<style lang="scss" scoped>
	@import '@/css/u-form.scss';
	
	.container {
		padding: 0rpx $app-page-padding $app-page-padding $app-page-padding;
		display: flex;
		flex-direction: column;
	}

	.children-view {
		width: 10rpx;
		flex: 1;
		display: flex;
		flex-direction: row;
	}

	.time-view{
		display: flex;
		flex-direction: column;
		
		font-size: 24rpx;
		font-weight: 400;
		color: #333333;
		
		.del{
			margin-left: 10rpx;
		}
	}
</style>
